from aiogram import Bot
from fluentogram import TranslatorRunner
from redis import asyncio as aioredis

from dc_shop.core.models.enums.order import OrderStatus
from dc_shop.core.utils.redis import get_redis_value
from dc_shop.database.services.order import OrderService
from dc_shop.database.services.user import UserService
from dc_shop.tg_bot.keyboards.inline import expired_payment_kb
from dc_shop.tg_bot.services.locale import Localizator
from dc_shop.tg_bot.services.tg_helpers import delete_msg_by_id, send_tg_message
from dc_shop.worker.exception_handler import exception_handler


@exception_handler
async def notify_expired_payment(
    ctx,
    user_tg_id: int,
    order_id: int,
) -> None:
    """Отправляем сообщение о просроченной оплате"""

    bot: Bot = ctx["bot"]
    redis: aioredis = ctx["redis"]
    localizator: Localizator = ctx["localizator"]
    user_service: UserService = ctx["user_service"]
    order_service: OrderService = ctx["order_service"]

    user = await user_service.get_user_by_telegram_id(user_tg_id)
    locale: TranslatorRunner = localizator.get_by_locale(user.lang_code)

    # Удаляем сообщение о истекающей оплате
    message = await get_redis_value(redis, f"{user_tg_id}_notifications")
    if message:
        await delete_msg_by_id(bot, message["message_id"], message["chat_id"])

    order = await order_service.get_order_by_id(order_id)
    if order and order.status == OrderStatus.created:
        await order_service.update_order_status(order_id, OrderStatus.payment_canceled)

        await send_tg_message(
            bot,
            user_tg_id,
            locale.get("payment-time-expired-msg"),
            reply_markup=expired_payment_kb(locale, order_id),
        )
